package com.miroservice.chapter2.web;


import com.miroservice.chapter2.common.HttpResponse;
import com.miroservice.chapter2.pojo.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1 api 的设计 一眼明了
 * 2 有版本
 * 3 控制层统一返回自定义的结果
 */
@RestController
@RequestMapping("/api/v1/user")
public class UserController {



    static Map<Long, User> userMap = new HashMap<Long, User>();


    /**
     * 列表请求
     * @return
     */
    @RequestMapping(path = "/list",method = RequestMethod.PUT, consumes = "application/json")
   // @GetMapping(consumes = "application/json")
    public HttpResponse list() {
        List<User> user = new ArrayList<>(userMap.values());
        return HttpResponse.ok().setData(user);
    }

    /**
     * 保存
     * @param user
     * @return
     */
    @PostMapping("/save")
    public HttpResponse save(@RequestBody User user) {
        userMap.put(user.getId(), user);
        return HttpResponse.ok();
    }

    /**
     * 获取单个用户
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public HttpResponse get(@PathVariable Long id) {
        final User user = userMap.get(id);
        return HttpResponse.ok().setData(user);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public HttpResponse delete(@PathVariable Long id) {
        userMap.remove(id);
        return HttpResponse.ok();
    }


}
